########################################## 
## STUDY 7
##########################################
########################################## 
setwd(getwd())
source("libraries.R")

#load data for study
data_raw <- haven::read_dta(here("Data", "study7.dta"))

##########################################
########################################## 
## Recode Variables
##########################################
########################################## 
df <- data_raw %>% 
  mutate(age = as.numeric(age),
         
         #Party Identification (1 = Democrat; 0 = Republican)
         repdem = case_when(
           demrep == 1 | repdem2 == 1 ~ 0,
           demrep == 2 | repdem2 == 2 ~ 1,
           TRUE ~ NA_real_
         ),
         
         ##Pre-registered attention checks
         
         #Low frequency behavior
         lowfreq = low_freq_q_1+low_freq_q_2 +low_freq_q_3+low_freq_q_4,
         overreport = case_when(
           lowfreq == 8 ~ 1,
           TRUE ~ 0
         ),
         
         #Color test
         attention = case_when(
           color=="puce" | color=="PUCE" | color=="Puce" | color==" puce" | color=="puce " ~ 1 ,
           TRUE ~ 0
         ),
         
         #Straight-lining
         straight = case_when(
           liste_exp_1<3 & liste_exp_2<3 & liste_exp_3<3 & liste_exp_4<3 ~ 1,
           liste_exp_1>3 & liste_exp_2>3 & liste_exp_3>3 & liste_exp_4>3 ~ 1,
           liste_exp_1==3 & liste_exp_2==3 & liste_exp_3==3 & liste_exp_4==3 ~ 1,
           TRUE ~ 0
         ),
         
         
         exclusion = case_when(
           overreport==1 | straight==1 | attention==0 ~ 1,
           TRUE ~ 0
         )) %>% 
  
  #Need for Chaos
  mutate(needchaos_9 = flip(needchaos_9),
         needchaos_10 = flip(needchaos_10)) %>% 
  mutate(nfc = rowMeans(select(., c("needchaos_1","needchaos_2", "needchaos_3", "needchaos_4", 
                                    "needchaos_5", "needchaos_6", "needchaos_7" ,"needchaos_9", "needchaos_10")), 
                        na.rm = TRUE)) %>% 
  
  #Feelings towards Democratic and Republican voters/elites
  mutate(Demvoters2=demVote_1+demVote_2+demVote_3+demVote_4-demVote_5-demVote_6,
         Repvoters2=repVote_1+repVote_2+repVote_3+repVote_4-repVote_5-repVote_6,
         Demelites2=eliteDem_1+eliteDem_2+eliteDem_3+eliteDem_4-eliteDem_5-eliteDem_6,
         Repelites2=eliteRep_1+eliteRep_2+eliteRep_3+eliteRep_4-eliteRep_5-eliteRep_6,
         Demvoters2R=demVote_R_1+demVote_R_2+demVote_R_3+demVote_R_4-demVote_R_5-demVote_R_6,
         Repvoters2R=repVote_R_1+repVote_R_2+repVote_R_3+repVote_R_4-repVote_R_5-repVote_R_6,
         Demelites2R=eliteDem_R_1+eliteDem_R_2+eliteDem_R_3+eliteDem_R_4-eliteDem_R_5-eliteDem_R_6,
         Repelites2R=eliteRep_R_1+eliteRep_R_2+eliteRep_R_3+eliteRep_R_4-eliteRep_R_5-eliteRep_R_6,
         Demvoters2Rrc=Demvoters2R*-1,
         Repvoters2Rrc=Repvoters2R*-1,
         Demelites2Rrc=Demelites2R*-1,
         Repelites2Rrc=Repelites2R*-1 
  ) %>% 
  mutate(across(.cols = c("Demvoters2Rrc", "Repvoters2Rrc", "Demelites2Rrc", "Repelites2Rrc", "Demvoters2", "Repvoters2", "Demelites2", "Repelites2"),
                ~ (zero1(.) %>% as.vector),
                .names = "{.col}01")) %>% 
  
  #Feelings towards Dem voters
  mutate(Demvoters = rowMeans(select(., c("Demvoters2Rrc01","Demvoters201")), 
                              na.rm = TRUE),
         
         #Feelings towards Rep voters
         Repvoters = rowMeans(select(., c("Repvoters2Rrc01","Repvoters201")), 
                              na.rm = TRUE),
         
         #Feelings towards Dem elites
         Demelites = rowMeans(select(., c("Demelites2Rrc01","Demelites201")), 
                              na.rm = TRUE),
         
         #Feelings towards Rep elites
         Repelites = rowMeans(select(., c("Repelites2Rrc01","Repelites201")), 
                              na.rm = TRUE),
         
         #Feeling abandoned by Republicans (if participant is Republican) and Democrats (if participant is Democrat)
         REP_ABANDON = rowMeans(select(., c("rep_abandon_1", "rep_abandon_2", "rep_abandon_3", "rep_abandon_4")), 
                                na.rm = TRUE),
         DEM_ABANDON = rowMeans(select(., c("dem_abandon_1", "dem_abandon_2", "dem_abandon_3", "dem_abandon_4")), 
                                na.rm = TRUE)
  ) %>% 
  mutate(ALL_ABANDON = rowMeans(select(., c("REP_ABANDON", "DEM_ABANDON")), 
                                na.rm = TRUE)) %>% 
  #Standardize variables
  mutate(across(.cols = c(Demvoters, Repvoters, Demelites, Repelites, REP_ABANDON, DEM_ABANDON, ALL_ABANDON, nfc, mob_dem_1, mob_dem_2, mob_rep_1, mob_rep_2),
                ~ (scale(.) %>%  as.vector),
                .names = "{.col}_zscore")) %>% 
  
  #Scale variables to range from 0 to 1
  mutate(across(.cols = c(Demvoters, Repvoters, Demelites, Repelites, REP_ABANDON, DEM_ABANDON, ALL_ABANDON, nfc, mob_dem_1, mob_dem_2, mob_rep_1, mob_rep_2),
                ~ (zero1(.) %>% as.vector),
                .names = "{.col}01")) %>% 
  filter(exclusion == 0) %>% 
  as.data.frame()

##########################################
########################################## 
## Sample Description 
## (See Supplementary Materials SM1, Table S2)
##########################################
########################################## 
#Gender
print(paste(round(mean(df$gender) - 1, 2)*100 , "percent of participants are female"))
#Age
print(paste("Mean age of participants:" , round(mean(df$age), 2), 
            ", SD:", round(sd(df$age) , 2) ))
#Education
print(paste("Less than high school:", round(prop.table(table(df$edu)), 2)[1]*100, "percent"   ))
print(paste("High school graduate:", round(prop.table(table(df$edu)), 2)[2]*100, "percent"   ))
print(paste(" Some college, but no degree:", round(prop.table(table(df$edu)), 2)[3]*100, "percent"   ))
print(paste("2 year college degree:", round(prop.table(table(df$edu)), 2)[4]*100, "percent"   ))
print(paste("4 year college degree:", round(prop.table(table(df$edu)), 2)[5]*100, "percent"   ))
print(paste("Graduate or professional degree:", round(prop.table(table(df$edu)), 2)[6]*100, "percent"   ))
#Ethnicity
print(paste("White/caucasian:", round(prop.table(table(df$race)), 2)[2]*100, "percent"   ))

##########################################
########################################## 
## Factor Analysis, etc.: Need for Chaos
##########################################
########################################## 
#Cronbach's alpha
nfc <- df %>% 
  select(needchaos_1:needchaos_10) %>% 
  psych::alpha(.) 

#Confirmatory factor analysis, Need for Chaos
cfa <- df %>% 
  select(needchaos_1:needchaos_10) %>% 
  na.omit()

#One-factor Model (Table S7)
m1  <- ' nfc_oneDim  =~ needchaos_1 + needchaos_2 + needchaos_3 + needchaos_4 + needchaos_5 + needchaos_6 + needchaos_7 + needchaos_9 + needchaos_10
        needchaos_3~~needchaos_4
        needchaos_3~~needchaos_5
        needchaos_4~~needchaos_5'
m1 <- lavaan::cfa(m1, data=cfa) 
m1_fit <- summary(m1 , fit.measures=TRUE) 

print(paste("One-factor model, Chi-square:" , round(m1_fit$FIT["chisq"],2 )))
print(paste("One-factor model, CFI:" , round(m1_fit$FIT["cfi"],2 )))
print(paste("One-factor model, TLI:" , round(m1_fit$FIT["tli"],2 )))
print(paste("One-factor model, RMSEA:" , round(m1_fit$FIT["rmsea"],2 )))

##########################################
########################################## 
## Remove 5% with highest Need for Chaos? (SM8)
## When set to TRUE, used for producing Fig S11
##########################################
##########################################
# Set to TRUE for excluding top 5% of participants with highest Need for Chaos
exclude_obs <- FALSE

if (exclude_obs == TRUE) {
  
  df <- df %>% 
    filter(nfc_zscore < quantile(nfc_zscore, probs = .95, na.rm = TRUE))
  
  print("Excluding top 5% observations with highest levels of the Need for Chaos")
  
}

##########################################
########################################## 
## Analysis - Fig. 6 of Main Text
##########################################
########################################## 
#Share Democratic rumor to hurt Democrats
mob_dem1 <-interflex(Y = "mob_dem_101", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                     data = df, 
                     estimator = "linear",
                     na.rm = TRUE,  
                     nbins = 7)

fig1_mob <- predict(mob_dem1, pool = TRUE, 
                    color = c("azure4", "black")) +
  ggtitle(expression(paste("Share ", bold("Democratic"), " Rumors to Mobilize Against Democrats"))) +
  xlab("Need for Chaos") +
  ylab("Mobilize against Democrats") +
  theme_bw() +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 17),
        axis.title.x = element_text(size = 17),
        axis.text.y = element_text(size = 12),
        axis.text.x = element_text(size = 12),
        legend.position = "none") +
  scale_color_manual(values=c("azure4", "black")) +
  annotate("text", x = .1, y = .27, label = "Democratic Identifier", size = 5.5, color = "black") +
  annotate("text", x = .2, y = .7, label = "Republican Identifier", size = 5.5, color = "azure4") +
  scale_y_continuous(breaks = c(0,0.2,.4,.6,.8), 
                     labels = c( "0", ".2", ".4", ".6", ".8"),
                     limits = c(-.2,.95)) 

#Share Democratic rumor to Expose Republicans
mob_dem2 <-interflex(Y = "mob_dem_201", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                     data = df, 
                     estimator = "linear",
                     na.rm = TRUE,  
                     nbins = 7)

fig2_mob <- predict(mob_dem2, pool = TRUE, 
                    color = c("azure4", "black")) +
  ggtitle(expression(paste("Share ", bold("Democratic"), " Rumors to Mobilize Against Republicans"))) +
  xlab("Need for Chaos") +
  ylab("Mobilize against Republicans") +
  theme_bw() +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 17),
        axis.title.x = element_text(size = 17),
        axis.text.y = element_text(size = 12),
        axis.text.x = element_text(size = 12),
        legend.position = "none") +
  scale_color_manual(values=c("azure4", "black")) +
  annotate("text", x = .1, y = .6, label = "Democratic Identifier", size = 5.5, color = "black") +
  annotate("text", x = .3, y = .15, label = "Republican Identifier", size = 5.5, color = "azure4") +
  scale_y_continuous(breaks = c(0,0.2,.4,.6,.8), 
                     labels = c( "0", ".2", ".4", ".6", ".8"),
                     limits = c(-.2,.95)) 

#Share Republican rumor to hurt Republicans
mob_rep1 <-interflex(Y = "mob_rep_101", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                     data = df, 
                     estimator = "linear",
                     na.rm = TRUE,  
                     nbins = 7)

fig3_mob <- predict(mob_rep1, pool = TRUE, 
                    color = c("azure4", "black")) +
  ggtitle(expression(paste("Share ", bold("Republican"), " Rumors to Mobilize Against Republicans"))) +
  xlab("Need for Chaos") +
  ylab("Mobilize against Republicans") +
  theme_bw() +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 17),
        axis.title.x = element_text(size = 17),
        axis.text.y = element_text(size = 12),
        axis.text.x = element_text(size = 12),
        legend.position = "none") +
  scale_color_manual(values=c("azure4", "black")) +
  annotate("text", x = .1, y = .7, label = "Democratic Identifier", size = 5.5, color = "black") +
  annotate("text", x = .2, y = .3, label = "Republican Identifier", size = 5.5, color = "azure4") +
  scale_y_continuous(breaks = c(0,0.2,.4,.6,.8), 
                     labels = c( "0", ".2", ".4", ".6", ".8"),
                     limits = c(-.2,.95)) 

#Share Republican rumor to Expose Democrats
mob_rep2 <-interflex(Y = "mob_rep_201", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                     data = df, 
                     estimator = "linear",
                     na.rm = TRUE,  
                     nbins = 7)

fig4_mob <- predict(mob_rep2, pool = TRUE, 
                    color = c("azure4", "black")) +
  ggtitle(expression(paste("Share ", bold("Republican"), " Rumors to Mobilize Against Democrats"))) +
  xlab("Need for Chaos") +
  ylab("Mobilize against Democrats") +
  theme_bw() +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 17),
        axis.title.x = element_text(size = 17),
        axis.text.y = element_text(size = 12),
        axis.text.x = element_text(size = 12),
        legend.position = "none") +
  scale_color_manual(values=c("azure4", "black")) +
  annotate("text", x = .2, y = .1, label = "Democratic Identifier", size = 5.5, color = "black") +
  annotate("text", x = .15, y = .6, label = "Republican Identifier", size = 5.5, color = "azure4") +
  scale_y_continuous(breaks = c(0,0.2,.4,.6,.8), 
                     labels = c( "0", ".2", ".4", ".6", ".8"),
                     limits = c(-.2,.95)) 

#Combine plots
ggarrange(fig1_mob,fig2_mob,fig3_mob,fig4_mob,
          ncol = 2, nrow=2) 

#Save plot
ggsave(here::here("figures", "fig6.pdf"),
       width = 11.5, height = 9)

## Regression Tables for Supplemental Materials (Table S17)
mob_dem1 <- lm(mob_dem_101 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 
mob_dem2 <- lm(mob_dem_201 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 

mob_rep1 <- lm(mob_rep_101 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 
mob_rep2 <- lm(mob_rep_201 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 

stargazer(mob_dem1 , mob_dem2 , mob_rep1 , mob_rep2 , 
          align=TRUE,
          no.space=TRUE,
          column.labels=c("Hurt Dem", "Expose Rep" , "Hurt Rep" , "Expose Dem"),
          covariate.labels = c("Need for Chaos (std.)" , "Party ID (1 = Dem.)" , "Gender (1 = Female)",
                               "Age", "Race", "Education", "NFC X PID", "NFC X Gender",
                               "NFC X Age", "NFC X Race", "NFC X Education", "Intercept"),
          keep.stat = c("n","ser"),
          dep.var.labels.include = FALSE)

##########################################
########################################## 
## Analysis - Fig S4 of Supplementary Materials
##########################################
########################################## 
#Feelings towards Democratic Voters
dem_voters <-interflex(Y = "Demvoters01", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                       data = df, 
                       estimator = "linear",
                       na.rm = TRUE,  
                       nbins = 7)

fig_dem_voters <- predict(dem_voters, pool = TRUE, 
                          color = c("red", "blue")) +
  ggtitle(expression(paste("Feelings towards ", bold("Democratic"), " Voters"))) +
  xlab("Need for Chaos") +
  ylab("Negative Feelings") +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 12),
        axis.title.x = element_text(size = 12),
        axis.text.y = element_text(size = 9),
        legend.position = "none") +
  annotate("text", x = .1, y = .2, label = "Democratic Identifier", size = 4, color = "blue") +
  annotate("text", x = .2, y = .6, label = "Republican Identifier", size = 4, color = "red")

#Feelings towards Democratic Elites
dem_elites <-interflex(Y = "Demelites01", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                       data = df, 
                       estimator = "linear",
                       na.rm = TRUE,  
                       nbins = 7)

fig_dem_elites <- predict(dem_elites, pool = TRUE, 
                          color = c("red", "blue")) +
  ggtitle(expression(paste("Feelings towards ", bold("Democratic"), " Elites"))) +
  xlab("Need for Chaos") +
  ylab("Negative Feelings") +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 12),
        axis.title.x = element_text(size = 12),
        axis.text.y = element_text(size = 9),
        legend.position = "none") +
  annotate("text", x = .1, y = .25, label = "Democratic Identifier", size = 4, color = "blue") +
  annotate("text", x = .2, y = .7, label = "Republican Identifier", size = 4, color = "red")

#Feelings Republican Voters
rep_voters <-interflex(Y = "Repvoters01", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                       data = df, 
                       estimator = "linear",
                       na.rm = TRUE,  
                       nbins = 7)

fig_rep_voters <- predict(rep_voters, pool = TRUE, 
                          color = c("red", "blue")) +
  ggtitle(expression(paste("Feelings towards ", bold("Republican"), " Voters"))) +
  xlab("Need for Chaos") +
  ylab("Negative Feelings") +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 12),
        axis.title.x = element_text(size = 12),
        axis.text.y = element_text(size = 9),
        legend.position = "none") +
  annotate("text", x = .1, y = .7, label = "Democratic Identifier", size = 4, color = "blue") +
  annotate("text", x = .2, y = .2, label = "Republican Identifier", size = 4, color = "red")

#Feelings Republican Elites
rep_elites <-interflex(Y = "Repelites01", X = "nfc_zscore", D="repdem", Z = c("gender","age","race","edu"),
                       data = df, 
                       estimator = "linear",
                       na.rm = TRUE,  
                       nbins = 7)

fig_rep_elites<- predict(rep_elites, pool = TRUE, 
                         color = c("red", "blue")) +
  ggtitle(expression(paste("Feelings towards ", bold("Republican"), " Elites"))) +
  xlab("Need for Chaos") +
  ylab("Negative Feelings") +
  theme(plot.title = element_text(size = 13),
        axis.title.y = element_text(size = 12),
        axis.title.x = element_text(size = 12),
        axis.text.y = element_text(size = 9),
        legend.position = "none") +
  annotate("text", x = .2, y = .75, label = "Democratic Identifier", size = 4, color = "blue") +
  annotate("text", x = .15, y = .25, label = "Republican Identifier", size = 4, color = "red")

#Combine plots
ggarrange(fig_dem_voters,fig_dem_elites,fig_rep_voters,fig_rep_elites,
          ncol = 2, nrow=2
) 

#Save plot
ggsave(here::here("figures", "figS4.pdf"),
       width = 12.5, height = 10)

## Regression Tables for Supplementary Materials (Table S18)
dem1 <- lm(Demvoters01 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 
dem2 <- lm(Demelites01 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 

rep1 <- lm(Repvoters01 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 
rep2 <- lm(Repelites01 ~ nfc_zscore*repdem + nfc_zscore*gender + nfc_zscore*age + nfc_zscore*race + nfc_zscore*edu , data =df) 

stargazer(dem1 , dem2 , rep1 , rep2 , 
          align=TRUE,
          no.space=TRUE,
          column.labels=c("Dem. Voters", "Dem. Elites" , "Rep. Voters" , "Rep. Elites"),
          covariate.labels = c("Need for Chaos (std.)" , "Party ID (1 = Dem.)" , "Gender (1 = Female)",
                               "Age", "Race", "Education", "NFC X PID", "NFC X Gender",
                               "NFC X Age", "NFC X Race", "NFC X Education", "Intercept"),
          keep.stat = c("n","ser"),
          dep.var.labels.include = FALSE)

##########################################
########################################## 
## Analysis - Table S19
##########################################
########################################## 
## Regression Tables for Appendix
all <- lm(ALL_ABANDON01 ~ nfc_zscore + gender + age + factor(race) + edu , data = df)

stargazer(all,
          align=TRUE,
          no.space=TRUE,
          keep=c("nfc_zscore", "gender", "age", "factor(race)", "edu"  , "Constant"),
          column.labels=c("Abandonment by In-Party"),
          covariate.labels = c("Need for Chaos (std.)" , "Gender" , "Age", "Ethnicity", "Education"),
          keep.stat = c("n","ser"),
          dep.var.labels.include = FALSE)












